<template>
  <div class="p-4">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="tel-connection-edit-form"
    >
      <el-form-item label="电联员工" prop="tel_connection_id">
        <el-select v-model="form.tel_connection_id" placeholder="请选择电联员工" style="width: 100%">
          <el-option
            v-for="item in telConnectionOptions"
            :key="item.id"
            :label="item.nickname || item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, PropType, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";

interface TelConnectionOption {
  id: number;
  username: string;
  nickname?: string;
}

interface FormData {
  tel_connection_id?: number;
}

const props = defineProps({
  currentValue: {
    type: Number,
    default: undefined
  },
  telConnectionOptions: {
    type: Array as PropType<TelConnectionOption[]>,
    default: () => []
  },
  onSubmit: {
    type: Function as PropType<(data: FormData) => void>,
    default: undefined
  }
});

const formRef = ref<FormInstance>();

const form = reactive<FormData>({
  tel_connection_id: undefined
});

// 监听当前值变化，初始化表单
watch(() => props.currentValue, (newValue) => {
  form.tel_connection_id = newValue;
}, { immediate: true });

// 表单验证规则
const rules = reactive<FormRules<FormData>>({
  // tel_connection_id 不是必填，可以为空
});

// 表单验证和提交
const handleSubmit = async (): Promise<boolean> => {
  if (!formRef.value) return false;
  
  try {
    await formRef.value.validate();
    if (props.onSubmit) {
      props.onSubmit({ ...form });
    }
    return true;
  } catch (error) {
    return false;
  }
};

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.tel_connection_id = props.currentValue;
};

// 获取表单数据
const getFormData = () => ({ ...form });

// 暴露方法给父组件
defineExpose({
  validateForm: handleSubmit,
  resetForm: handleReset,
  getFormData
});
</script>

<style scoped>
.tel-connection-edit-form {
  max-height: 400px;
  overflow-y: auto;
}
</style> 